<?php
/**
 * Erstellung und verwaltung Admin-Accounts
 *
 * @author		Joachim Ruf
 * @copyright	Copyright (c) 2003-2013 Loresoft Software (http://www.loresoft.de)
 * @license		http://yapary.loresoft.de/lizenzbedingungen     New BSD License
 *
 * */


Class Yapary_Admin_AdminAccountList
{
    /* @var $oSql Yapary_Database_Sql */
    private $oSql           = NULL;
    /** @var sqlId string */
    private $sqlId          = NULL;
    /** @var $dbTableName string */
    private $dbTableName    = 'yapary_admin_account';


    /**
     * @param Object $_oSql	: Datenbankklasse fuer Datenbankzugriff
     * */
    function __construct (Yapary_Db_Sql_Connector $_oSql)
    {
        $this->oSql  = $_oSql;
        $this->sqlId = substr(md5(microtime()), 0, 15);
    }


    /**
     * Fuegt einen neuen Eintrag hinzu
     * @return Yapary_Admin_AdminAccount|NULL
     * @param string $_name		: Administrationsname
     * @param string $_password	: Administratorpasswort
     * @param string $_email	: Administrator Email-Adresse
     * @return bool|NULL|Yapary_Admin_AdminAccount
     * */
    public function add ($_name, $_password, $_email = '')
    {
	    $nameLength  = strlen($_name);
	    $passLength = strlen($_password);

		if ($nameLength < 4 || $nameLength > 25) {
			return false;
		}
		if ($passLength < 6 || $passLength > 15) {
			return false;
		}
		if (is_numeric($_password)) {
			return NULL;
		}

		$oDbResult = $this->oSql->request('INSERT INTO '.$this->dbTableName.'
                    			 (Name, Md5Password, Email, LoginDateTime, LastLoginDateTime, Status, RegDate)
                    			 VALUES (:name, :md5Password, :email, :loginDateTime, :lastLoginDateTime, :status,:regDate) ',
			                            array('name'              => $_name,
			                                  'md5Password'       => md5($_password),
			                                  'email'             => $_email,
			                                  'loginDateTime'     => date("Y-m-d H:i:s"),
			                                  'lastLoginDateTime' => 'admin_acount.LoginDateTime',
			                                  'status'            => 0,
			                                  'regDate'           => date("Y-m-d")),
                                         $this->sqlId);
		return new Yapary_Admin_AdminAccount($this->oSql, $oDbResult->getLastInsertId());

        return NULL;
    }


    /**
     * Loescht einen existierenden Eintrag
     * @param int $_id	: Id des zu loeschenden Eintrags
     * @return bool
     * */
    public function delete ($_id)
    {
        $i = 0;
        $oPriority = $this->get($_id);
        $arr = $this->getList($oPriority->getName());

        $count = count($arr);
        $oDbResult = $this->oSql->request('DELETE
                					    FROM '.$this->dbTableName.'
                					    WHERE Id=:id',
                                      array('id' => $_id),
                                      $this->sqlId);

        return true;
    }


    /**
     * Liefert einen Datensatz anhand der Id
     * @param int $_id	: Id des auszugebenden Eintrags
     * @return Yapary_Admin_AdminAccount
     * */
    public function get ($_id)
    {
        $oDbResult = $this->oSql->request('SELECT *
        					  FROM '.$this->dbTableName.' t1
        					  WHERE Id=:id',
                            array('id' => $_id),
                            $this->sqlId);

        if ($oDbResult->getCount() == 1) {
            $row = $this->oSql->getData($this->sqlId);
            return new Yapary_Admin_AdminAccount($this->oSql, $row);
        }

        return NULL;
    }


    /**
     * Liefert alle Datensaetz der 2.Kategorie
     * @param string $_orderBy	: Name der Relation nach welcher sortiert werden soll, inklusive Mysql definition DESC
     * @return Array[Yapary_Admin_AdminAccount]
     * */
    public function getList ($_orderBy = 'Name')
    {
        $arrResult = array();
        $_orderBy = (preg_match('/^([a-zA-Z-_ ]+)([a-zA-Z-_0-9 ]*)$/', $_orderBy)) ? ' ORDER BY '.$_orderBy : '';

        $oDbResult = $this->oSql->request('SELECT *
        					  FROM '.$this->dbTableName.' t1
        					  '.$_orderBy.'',
                            array(),
                            $this->sqlId);

        if ($oDbResult->getCount() >= 1) {
            while ($row = $oDbResult->getNext()) {
                $arrResult[] = new Yapary_Admin_AdminAccount($this->oSql, $row);
            }
        }

        return $arrResult;
    }


    /**
     * Ermittelt die Anzahl an Eintaegen
     * @return int
     * */
    public function getCount ()
    {
        $oDbResult = $this->oSql->request('SELECT Id
        					  FROM '.$this->dbTableName.' t1',
                            array(),
                            $this->sqlId);

        return $oDbResult->getCount();
    }


	/**
	* Loggt einen registrierten Administrator ein
	* @param string $name {4-25} : Administratorname
	* @param string $password {6-15} : Administratorpasswort
	* @return string($sessionId)|NULL
	*/
	public function login ($name, $password)
	{
	    $nameLength  = strlen($name);
	    $passLength = strlen($password);

		if ($nameLength < 4 || $nameLength > 25) {
			return false;
		}
		if ($passLength < 6 || $passLength > 15) {
			return false;
		}

		$oDbResult = $this->oSql->request('SELECT *
							FROM '.$this->dbTableName.'
							WHERE Name=:name AND
								  Md5Password=:md5Password',
		                    array('name'        => $name,
		                          'md5Password' => md5($password)));

		if ($oDbResult->getCount() == 1) { // Einloggen, wenn Benutzerdaten korrekt
			$row = $oDbResult->getNext();

			// --- Speichere neue Login-Daten in Datenbank ---
			$id = md5(microtime());
			$oDbResult = $this->oSql->request('UPDATE '.$this->dbTableName.'
								SET SessionId=:id
								WHERE Name=:name AND
									  Md5Password=:md5Password',
			                    array(
			                    		'id'          => $id,
			                    	  	'name'        => $name,
			                          	'md5Password' => md5($password)
			                    ));

			return $id;
		}

		return false;
	}


	/**
	* Loggt einen registrierten Administrator aus
	* @param string $name {4-25} : Administratorname
	* @param string $sessionId {32} : Beim login vergebene SessionId
	* @return bool
	*/
	public function logout ($name, $sessionId)
	{
	    $nameLength  = strlen($name);
	    $sessLength = strlen($sessionId);

		if ($nameLength < 4 || $nameLength > 25) {
			return false;
		}
		if ($sessLength != 32) {
			return false;
		}

		if ($this->isLoggedIn($name, $sessionId)) {

			// Speichere neue Login-Daten in Datenbank
			$id = md5(microtime());
			$oDbResult = $this->oSql->request('UPDATE '.$this->dbTableName.'
										SET SessionId=:id
										WHERE Name=:name AND
											  SessionId=:sessionId',
			                            array('id'        => $id,
			                            	  'name'      => $name,
			                                  'sessionId' => $sessionId
			                            	));
			return true;
		}

		return false;
	}


	/**
	* Prueft ob ein Administrator eingeloggt ist
	* @param string $name : Administratorname
	* @param string $sessionId : Erhaltene SessionId beim Login
	* @return bool
	*/
	public function isLoggedIn ($name, $sessionId)
	{
	    $nameLength  = strlen($name);
	    $sessLength = strlen($sessionId);

		if ($nameLength < 4 || $nameLength > 25) {
			return false;
		}
		if ($sessLength != 32) {
			return false;
		}

		$oDbResult = $this->oSql->request('SELECT Id
							FROM '.$this->dbTableName.'
							WHERE Name=:name AND
								  SessionId=:sessionId',
		                    array('name'      => $name,
		                          'sessionId' => $sessionId));

		if ($oDbResult->getCount() == 1) {
			return true;
		}

		return false;
	}


}


?>